import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { AcceptanceManageContext } from '../mconfig/useManageContext';
import { DescriptionsType } from '@/components/DescriptionsType';
import { changeNumMoneyToChinese, getLoadMapList, getSelectDataMapList, getTenantID, wordHandChildParam, wordToChildParams } from '@/utils';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { getLandUpdateConfig } from '../mconfig/LandForm';
import { connect } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Button, Space } from 'antd';
import { AcceptanceManageAPI } from '../common/type';
import { SaveOutlined } from '@ant-design/icons';
import { ILoadMapTypeAll } from '@/common';
import { addAssetMaterielService, editAssetMaterielService } from '../services';
import moment from 'moment';
import {
  getCarUpdateConfig,
  getEquipmentFurnitureUpdateConfig,
  getHouseUpdateConfig,
  getInvestUpdateConfig,
  getInvisibleUpdateConfig,
  getLeaseHouseUpdateConfig,
  getLeaseLandUpdateConfig,
  getOtherUpdateConfig,
  getProjectUpdateConfig,
  getStockpileUpdateConfig,
} from '../mconfig';

const AcceptUpdateView: React.FC<any> = ({ curRes, locationProps }: AcceptanceManageAPI.AcceptRouterDataType) => {
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';
  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方法
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //计量单位
    `${getTenantID()}${ILoadMapTypeAll.ASSET_PURCHASE_TYPE}`, //采购方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_ACQUIRE_TYPE}`, //取得形式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_VALUE_TYPE}`, //价值类型
    `${getTenantID()}${ILoadMapTypeAll.ASSET_CAR_TYPE}`, //车辆类型
    `${getTenantID()}${ILoadMapTypeAll.ASSET_USE_TYPE}`, //使用权类型
  ]);
  /** 折旧方法 */
  const averageLifeMethod = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`], 'name', 'id', true);
  /** 采购方式 */
  const assetPurchaseType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_PURCHASE_TYPE}`], 'name', 'id', true);
  /** 取得形式 */
  const assetAcquireType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_ACQUIRE_TYPE}`], 'name', 'id', true);
  /** 价值类型 */
  const assetValueType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_VALUE_TYPE}`], 'name', 'id', true);
  /** 车辆类型 */
  const assetCarType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_CAR_TYPE}`], 'name', 'id', true);
  /** 使用权类型 */
  const assetUseType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_USE_TYPE}`], 'name', 'id', true);
  /** 共通表单数据 */
  const [bothForm] = Form.useForm();
  /** 材料表单数据 */
  const [assetLandForm] = Form.useForm(); // 土地
  const [assetHouseForm] = Form.useForm(); // 房屋
  const [assetCarForm] = Form.useForm(); // 车辆
  const [assetEquipmentFurnitureForm] = Form.useForm(); // 设备及家具
  const [assetOtherForm] = Form.useForm(); // 其他固定资产
  const [assetInvisibleForm] = Form.useForm(); // 专利及信息数据等无形资产
  const [assetProjectForm] = Form.useForm(); // 在建工程
  const [assetLeaseLandForm] = Form.useForm(); // 租赁土地
  const [assetLeaseHouseForm] = Form.useForm(); // 租赁房屋
  const [assetStockpileForm] = Form.useForm(); // 政府储备物资
  const [assetInvestForm] = Form.useForm(); // 长期投资
  /** 当前材料类型 */
  const [selectAssetType, setSelectAssetType] = useState<string>('100124021000');
  const changeAssetType = (value: string, node?: any) => {
    /** 清空表单 */
    selectAssetType === '100124021000' && assetLandForm?.setFieldsValue({});
    selectAssetType === '100124021001' && assetHouseForm?.setFieldsValue({});
    selectAssetType === '100124021002' && assetCarForm?.setFieldsValue({});
    selectAssetType === '100124021003' && assetEquipmentFurnitureForm?.setFieldsValue({});
    selectAssetType === '100124021004' && assetOtherForm?.setFieldsValue({});
    selectAssetType === '100124021005' && assetInvisibleForm?.setFieldsValue({});
    selectAssetType === '100124021006' && assetProjectForm?.setFieldsValue({});
    selectAssetType === '100124021007' && assetLeaseLandForm?.setFieldsValue({});
    selectAssetType === '100124021008' && assetLeaseHouseForm?.setFieldsValue({});
    selectAssetType === '100124021009' && assetStockpileForm?.setFieldsValue({});
    selectAssetType === '100124021010' && assetInvestForm?.setFieldsValue({});
    /** 更新类型 */
    setSelectAssetType(value);
  };
  /** 获取表单配置
   *  @leftSelectName    左侧仓库名称
   *  @record   当前项
   *  @pageType  当前的页面类型
   *  @bothForm  共通表单实例
   */
  /** 公共表单 */
  const { bothConfig, bothMethods } = getUpdateConfig({
    leftSelectName: locationProps?.state?.leftSelectName ? locationProps?.state?.leftSelectName[0] : '',
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    bothForm,
    changeAssetType,
  });
  /** 土地 */
  const { landConfig, landMethods } = getLandUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetLandForm,
    mapLoading,
    assetPurchaseType,
    assetAcquireType,
    assetValueType,
  });
  /** 房屋 */
  const { houseConfig, houseMethods } = getHouseUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetHouseForm,
    mapLoading,
    assetPurchaseType,
    assetAcquireType,
    assetValueType,
  });
  /** 车辆 */
  const { carConfig, carMethods } = getCarUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetCarForm,
    mapLoading,
    assetPurchaseType,
    assetAcquireType,
    assetValueType,
    assetCarType,
  });
  /** 设备及家具 */
  const { equipmentFurnitureConfig, equipmentFurnitureMethods } = getEquipmentFurnitureUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetEquipmentFurnitureForm,
    mapLoading,
    assetPurchaseType,
    assetAcquireType,
    assetValueType,
  });
  /** 其他固定资产 */
  const { otherConfig, otherMethods } = getOtherUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetOtherForm,
    mapLoading,
    assetPurchaseType,
    assetAcquireType,
    assetValueType,
  });
  /** 专利及信息数据等无形资产 */
  const { invisibleConfig, invisibleMethods } = getInvisibleUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetInvisibleForm,
    mapLoading,
    assetPurchaseType,
    assetAcquireType,
    assetValueType,
  });
  /** 在建工程 */
  const { projectConfig, projectMethods } = getProjectUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetProjectForm,
    mapLoading,
    assetValueType,
  });
  /** 租赁土地 */
  const { leaseLandConfig, leaseLandMethods } = getLeaseLandUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetLeaseLandForm,
    mapLoading,
    assetAcquireType,
  });
  /** 租赁房屋 */
  const { leaseHouseConfig, leaseHouseMethods } = getLeaseHouseUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetLeaseHouseForm,
    mapLoading,
    assetAcquireType,
  });
  /** 政府储备物资 */
  const { stockpileConfig, stockpileMethods } = getStockpileUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetStockpileForm,
    mapLoading,
    assetValueType,
  });
  /** 长期投资 */
  const { investConfig, investMethods } = getInvestUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    assetInvestForm,
    mapLoading,
    assetValueType,
  });

  /** 添加编辑回调 */
  const updateCallback = (res: any, clickType: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      // reloadDetail();
    } else {
      message.error(res?.msg);
    }
  };
  /** 添加接口 */
  const { addAssetMaterielLoading, addAssetMaterielRun } = addAssetMaterielService(updateCallback);
  /** 编辑接口 */
  const { editAssetMaterielLoading, editAssetMaterielRun } = editAssetMaterielService(updateCallback);
  /** 暂存 */
  const submitForm = () => {
    let bothData: any = {};
    bothForm?.validateFields()?.then((res: any) => {
      bothData = JSON.parse(JSON.stringify(res));
      if (locationProps?.state?.pageType === 'add') {
        bothData.assetStoreId = locationProps?.state?.leftSelectKeys[0];
      }
      /** 判断当前的表单 */
      let form: any = null;
      bothData.assetType === '100124021000' && (form = assetLandForm);
      bothData.assetType === '100124021001' && (form = assetHouseForm);
      bothData.assetType === '100124021002' && (form = assetCarForm);
      bothData.assetType === '100124021003' && (form = assetEquipmentFurnitureForm);
      bothData.assetType === '100124021004' && (form = assetOtherForm);
      bothData.assetType === '100124021005' && (form = assetInvisibleForm);
      bothData.assetType === '100124021006' && (form = assetProjectForm);
      bothData.assetType === '100124021007' && (form = assetLeaseLandForm);
      bothData.assetType === '100124021008' && (form = assetLeaseHouseForm);
      bothData.assetType === '100124021009' && (form = assetStockpileForm);
      bothData.assetType === '100124021010' && (form = assetInvestForm);
      form?.validateFields()?.then((values: any) => {
        if (Object.keys(bothData).length !== 0) {
          values.depreciationMethod = '100124041000';
          let obj = JSON.parse(JSON.stringify(values));
          let objectKeysArr = Object.keys(obj);
          let filterArr = objectKeysArr.filter((item: string) => {
            return item.substring(item.length - 4) === 'Date';
          });
          for (let i = 0; i < filterArr.length; i++) {
            obj[filterArr[i]] = obj[filterArr[i]] ? moment(obj[filterArr[i]])?.format('YYYY-MM-DD') : '';
          }
          obj.hasOwnProperty('warrantyDeadline') && (obj.warrantyDeadline = obj.warrantyDeadline ? moment(obj.warrantyDeadline)?.format('YYYY-MM-DD') : '');
          bothData.assetjson = JSON.parse(JSON.stringify(obj));
        }
        /** 初始数量和剩余数量 */
        bothData.residueNum = bothData.quantityOrArea;
        if (locationProps?.state?.pageType === 'edit') {
          let record = JSON.parse(JSON.stringify(locationProps?.state?.record ? locationProps?.state?.record : {}));
          let data = { ...record, ...bothData };
          editAssetMaterielRun(data);
        } else {
          addAssetMaterielRun(bothData);
        }
      });
    });
  };

  useEffect(() => {
    changeAssetType(locationProps?.state?.record ? locationProps?.state?.record.assetType : '100124021000');
  }, []);

  return (
    <>
      <Spin spinning={false}>
        <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
          <Col span={24} className={`${styleFixCls}row-col`}>
            <Tabs
              className={pageStyles['commonTabs']}
              type="card"
              onChange={(activeKey: string) => {}}
              items={[
                {
                  label: '基本信息',
                  key: '001',
                  children: (
                    <>
                      <div className="commonTabsBodyDom">
                        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
                          <ScrollBarLayout style={{ padding: '5px 20px' }}>
                            <DescriptionsType config={bothConfig} key={0} />
                            {selectAssetType === '100124021000' && <DescriptionsType config={landConfig} key={1} />}
                            {selectAssetType === '100124021001' && <DescriptionsType config={houseConfig} key={2} />}
                            {selectAssetType === '100124021002' && <DescriptionsType config={carConfig} key={3} />}
                            {selectAssetType === '100124021003' && <DescriptionsType config={equipmentFurnitureConfig} key={4} />}
                            {selectAssetType === '100124021004' && <DescriptionsType config={otherConfig} key={5} />}
                            {selectAssetType === '100124021005' && <DescriptionsType config={invisibleConfig} key={6} />}
                            {selectAssetType === '100124021006' && <DescriptionsType config={projectConfig} key={7} />}
                            {selectAssetType === '100124021007' && <DescriptionsType config={leaseLandConfig} key={8} />}
                            {selectAssetType === '100124021008' && <DescriptionsType config={leaseHouseConfig} key={9} />}
                            {selectAssetType === '100124021009' && <DescriptionsType config={stockpileConfig} key={10} />}
                            {selectAssetType === '100124021010' && <DescriptionsType config={investConfig} key={11} />}
                          </ScrollBarLayout>
                        </div>
                        <div className="tabsBodyBottomBtn">
                          <Space>
                            <Button
                              type={'primary'}
                              icon={<SaveOutlined />}
                              disabled={locationProps?.state?.pageType === 'view'}
                              loading={addAssetMaterielLoading || editAssetMaterielLoading}
                              onClick={submitForm}
                            >
                              暂存
                            </Button>
                          </Space>
                        </div>
                      </div>
                    </>
                  ),
                },
              ]}
              destroyInactiveTabPane={true}
            />
          </Col>
        </Row>
      </Spin>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AcceptUpdateView);
